home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10885 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  83 lines

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: cout << tab(5) ... without OMANIP(int)
  5. Date: Sat, 09 Mar 1996 21:15:53 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.00000064.0003e721@fred>
  8. References: <Bentley_Joe-0503961032270001@129.197.157.33>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client79.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <Bentley_Joe-0503961032270001@129.197.157.33>, 
  14. Bentley_Joe@mm.rdd.lmsc.lockheed.com (Joe Bentley) wrote:
  15. > I would like to write a tab function/manipulator that I can use in an
  16. > output stream.  I know how to do this using the OMANIP(int) macro
  17. > approach, but would like another solution.  I assumed that I could do it
  18. > with a function template, but I'm not sure how to approach the problem. 
  19. > Any ideas?
  20.  
  21. manipulators with arguments are two phases process: first create a 
  22. temporary object that will store the parameters then have an ostream& 
  23. operator <<(ostream&, const object&) that will do the actual job.
  24.  
  25. The most simple way for a stand-alone manipulator:
  26.  
  27. class tab
  28. {
  29.   friend ostream& operator <<(ostream&, const tab&);
  30.   int arg;
  31. public:
  32.   tab(int a) : arg(a) {}
  33. };
  34.  
  35. ostream& operator <<(ostream& os, const tab& t)
  36. {
  37.   // t.arg contain the argument
  38.   // job here
  39. }
  40.  
  41. so: "ostream << tab(5);" will create a temporary object of class "tab" and 
  42. call the operator <<.
  43.  
  44.  
  45.  
  46. A generic object can be used for all manipulator with an int parameter:
  47.  
  48. class omanip_int
  49. {
  50.   friend ostream& operator <<(ostream&, const omanip_int&);
  51.   typedef ostream& (*pfnType)(ostream&, int);
  52.   pfnType pfn;
  53.   int arg;
  54. public:
  55.   omanip_int(pfnType fn, int a) : pfn(fn), arg(a) {}
  56. };
  57.  
  58. inline ostream& operator <<(ostream& os, const omanip_int& om)
  59. { return (*pfnType)(os, arg); }
  60.  
  61. (Of course, this class can be easily templatized to handle any kind of 
  62. argument)
  63.  
  64. So manipulators can be defined more simply as:
  65.  
  66. ostream& tab_exec(ostream& os, int arg)
  67. {
  68.   // job to do
  69.   return os;
  70. }
  71.  
  72. inline omanip_int tab(int arg)
  73. { return omanip_int(&tab_exec, arg); }
  74.  
  75.  
  76. I hope this'll help.
  77.  
  78.  Frederic LACHASSE (ECP 86)
  79.  CompuServe: 100530,2005
  80.  Internet: lachass@worldnet.fr
  81.  
  82.